<template>
  <div style="width:100%;height:100%;" ref="myEchart"></div>
</template>
<script>
import Chart from "echarts";
export default {
  data() {
    return {
      chart: null,
      option: {},
      datas: {
        title: "总产值分析", //主标题
        // subtext: "单位（万元）", //副标题
        legend: ["出库量", "采购量"], //折线名字
        xData: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月"
        ], //x轴数据
        yData: [],
        subtextSelf: ''
      }
    };
  },
  props: { plan_table: { type: Array, default: ()=>[] }, subtext: { type: String, default: '万元' } },
  created() {
    this.subtextSelf = this.subtext === '' ? '单位（万元）' : '单位（'+this.subtext+'）'
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      this.chart = Chart.init(this.$refs.myEchart);
      this.chart.setOption({
        grid:{
          left:'16%'
        },
        title: {
          text: this.datas.title,
          subtext: this.subtextSelf
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: this.datas.legend
        },
        calculable: true,
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: this.datas.xData
          }
        ],
        yAxis: { type: "value" },
        series: this.plan_table
      });
    }
  },
  watch: {
    plan_table() {
      this.initChart();
    },
    subtext(val) {
      this.subtextSelf = val === '' ? '单位（万元）' : '单位（'+val+'）'
      this.chart.setOption({
        grid:{
          left:'16%'
        },
        title: {
          text: this.datas.title,
          subtext: this.subtextSelf
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: this.datas.legend
        },
        calculable: true,
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: this.datas.xData
          }
        ],
        yAxis: { type: "value" },
        series: this.plan_table
      });
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  }
};
</script>
